package observer;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * These ints can be observed by {@link BooleanObserver}s, i.e. the observers will be notified of any changes.
 *
 * @author Neil Dickson
 */
public final class ObservedBoolean implements Copiable<ObservedBoolean>, Serializable {
	private boolean						value;
	private ArrayList<BooleanObserver>	observers;

	public ObservedBoolean(boolean b) {
		value = b;
		observers = null;
	}

	public synchronized void addObserver(BooleanObserver observer) {
		if (observer==null) {
			throw new NullPointerException();
		}
		if (observers==null) {
			observers = new ArrayList<BooleanObserver>();
		}
		if (!observers.contains(observer)) {
			observers.add(observer);
		}
	}
	public synchronized void removeObserver(BooleanObserver observer) {
		if (observers!=null && observers.contains(observer)) {
			observers.remove(observer);
		}
	}

	public boolean get() {
		return value;
	}
	public void set(boolean b) {
		set(null,b);
	}
	public void set(BooleanObserver culprit,boolean b) {
		value = b;
		updateAllBut(culprit);
	}

	public ObservedBoolean copy() {
		return new ObservedBoolean(value);
	}

	private void updateAllBut(BooleanObserver culprit) {
		if (observers!=null) {
			for (BooleanObserver observer : observers) {
				if (observer!=culprit) {
					observer.valueChanged(this);
				}
			}
		}
	}
}
